package com.jiaqi789.blelego;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions.RxPermissions;

import rx.functions.Action1;

public class MainActivity extends AppCompatActivity {
	private boolean isGotPermission;
	private BluetoothAdapter mBluetoothAdapter;
	private BluetoothManager bluetoothManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Logger.init("lego");
		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(this, "ble not supported", Toast.LENGTH_SHORT).show();
			finish();
		}
		RxPermissions rxPermissions = new RxPermissions(this);
		rxPermissions
				.request(Manifest.permission.ACCESS_FINE_LOCATION)
				.subscribe(new Action1<Boolean>() {
					@Override
					public void call(Boolean aBoolean) {
						isGotPermission = aBoolean;
						if (aBoolean) {
							Logger.d("已经获取了权限");
							bluetoothManager =
									(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
							mBluetoothAdapter = bluetoothManager.getAdapter();
						} else Logger.e("没有获取权限");
					}
				}, new Action1<Throwable>() {
					@Override
					public void call(Throwable throwable) {
						Logger.e(throwable.getMessage());
					}
				});
	}

	public void search(View view) {
		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, 123);
		}
		Logger.d("START SCAN");
		mBluetoothAdapter.startLeScan(mLeScanCallback);
	}

	private BluetoothAdapter.LeScanCallback mLeScanCallback =
			new BluetoothAdapter.LeScanCallback() {
				@Override
				public void onLeScan(final BluetoothDevice device, int rssi,
									 byte[] scanRecord) {
					Logger.d("deivce" + device);
				}
			};
}
